﻿Imports System.IO

Module Patcher

    Private enableData() As Byte = {
        &HE8, &H4B, &H9D, &H1, &H0, &H90, &H90, &H90, &H90, &H90,
        &H66, &H32, &H5F, &H72, &H65, &H73, &H2E, &H64, &H6C, &H6C,
        &H0, &H0, &H0, &H0, &H0, &H0, &H68, &HC0, &HE1, &H4F, &H0, &H2E, &HFF, &H15, &HC, &H2, &H6C, &H0, &HC7, &H5, &H88, &H27, &H6B, &H0, &H0, &HE7, &H4D, &H0, &HC3
    }

    Private disableData() As Byte = {&HC7, &H5, &H88, &H27, &H6B, &H0, &H0, &HE7, &H4D, &H0}

    Private Function CheckValid(fs As FileStream, close As Boolean) As Boolean
        ' проверить валидность файла
        If (fs.Length < 1040600L) Then
            If (close) Then fs.Close()
            Return False
        End If

        fs.Seek(1040600, SeekOrigin.Begin) ' 0x50FAD8 GNW95MUTEX

        Dim str = "GNW95MUTEX"
        For i = 0 To 9
            Dim c = Chr(fs.ReadByte())
            If (c <> str(i)) Then
                fs.Close()
                Return False
            End If
        Next

        If (close) Then fs.Close()

        Return True
    End Function

    Public Function CheckValid(exe As String) As Boolean
        Return CheckValid(File.Open(exe, FileMode.Open, FileAccess.Read, FileShare.Read), True)
    End Function

    Public Function ToggleHiResPatch(exe As String, enable As Boolean) As Boolean
        Dim bw As BinaryWriter = New BinaryWriter(File.Open(exe, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))

        ' проверить валидность файла
        If (CheckValid(bw.BaseStream, False) = False) Then
            bw.Close()
            Return False
        End If

        bw.Seek(870528, SeekOrigin.Begin) ' 0x4E4480

        If (enable) Then
            bw.Write(enableData, 0, 10)
            ' 0x4FE1C0 - 0x4FE1E7
            bw.Seek(976320, SeekOrigin.Begin)
            bw.Write(enableData, 10, 39)
        Else
            bw.Write(disableData)
            ' 0x4FE1C0 - 0x4FE1E7
            bw.Seek(976320, SeekOrigin.Begin)
            For count = 1 To 10
                bw.Write(0)
            Next
        End If

        bw.Close()
        Return True
    End Function

    Public Function IsEnabledHRP(exe As String) As Boolean
        Dim br As BinaryReader = New BinaryReader(File.Open(exe, FileMode.Open, FileAccess.Read, FileShare.Read))

        ' 0x4FE1C0
        If (br.BaseStream.Length < 976320L) Then
            br.Close()
            Return False
        End If

        br.BaseStream.Seek(976320, SeekOrigin.Begin)

        For i = 10 To 19
            If br.ReadByte() <> enableData(i) Then
                br.Close()
                Return False
            End If
        Next

        br.Close()
        Return True
    End Function

End Module
